package com.huawei.struts.dao;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.st.model.UserT;

/**
 * A data access object (DAO) providing persistence and search support for UserT
 * entities. Transaction control of the save(), update() and delete() operations
 * can directly support Spring container-managed transactions or they can be
 * augmented to handle user-managed Spring transactions. Each of these methods
 * provides additional information for how to configure it for the desired type
 * of transaction control.
 * 
 * @see com.st.model.UserT
 * @author MyEclipse Persistence Tools
 */

public class UserTDAO extends HibernateDaoSupport {
	private static final Log log = LogFactory.getLog(UserTDAO.class);
	// property constants
	public static final String SNAME = "sname";
	public static final String SPASSWORD = "spassword";

	protected void initDao() {
		// do nothing
	}

	/**
	 * 保存
	 * @param transientInstance
	 */
	public void save(UserT transientInstance) {
		log.debug("saving UserT instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	/**
	 * 修改
	 * @param persistentInstance
	 */
	public void delete(UserT persistentInstance) {
		log.debug("deleting UserT instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	/**
	 * 根据ID得到详细信息
	 * @param id
	 * @return
	 */
	public UserT findById(java.lang.Integer id) {
		log.debug("getting UserT instance with id: " + id);
		try {
			UserT instance = (UserT) getHibernateTemplate().get(
					"com.st.model.UserT", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding UserT instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from UserT as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findBySname(Object sname) {
		return findByProperty(SNAME, sname);
	}

	public List findBySpassword(Object spassword) {
		return findByProperty(SPASSWORD, spassword);
	}

	 
	
	public List queryForPage(final int offset,
			final int length,final UserT user) {
		List list = getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				StringBuffer hql=new StringBuffer();
				hql.append("from UserT u where 1=1");
				Query query=queryMap(hql,user,session);
				query.setFirstResult(offset);
				query.setMaxResults(length);
				List list = query.list();
				return list;
			}
		});
		return list;
	}
	
	
	public List export(final UserT user) {
		List list = getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				StringBuffer hql=new StringBuffer();
				hql.append("from UserT u where 1=1");
				Query query=queryMap(hql,user,session);
				List list = query.list();
				return list;
			}
		});
		return list;
	}
	
	public Integer getAllRowCount(final UserT user) {
		Integer count = (Integer)getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				StringBuffer hql=new StringBuffer();
				hql.append("select count(*) from UserT u where 1=1");
				Query query=queryMap(hql,user,session); 
				return  Integer.parseInt(query.iterate().next().toString());
			}
		});
		return count;
	}
	
	public boolean login(final UserT user) {
		Integer count = (Integer)getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				StringBuffer hql=new StringBuffer();
				hql.append("select count(*) from UserT u where 1=1");
				Query query=loginQueryMap(hql,user,session); 
				return  Integer.parseInt(query.iterate().next().toString());
			}
		});
		return count>0?true:false;
	}
	
	public  Query queryMap(final StringBuffer hql,final UserT user,Session session)
	{
		Map map=new HashMap();
		if(user.getSname()!=null && user.getSname().length()>0)
		{
			map.put("name", "%"+user.getSname()+"%");
		    hql.append(" and u.sname like :name");
		}
		Query query = session.createQuery(hql.toString());
		
		Iterator it = map.keySet().iterator();

         while (it.hasNext()){

         Object key = it.next(); 

         query.setParameter(key.toString(), map.get(key)); 

         }
         return query;
	}
	
	public  Query loginQueryMap(final StringBuffer hql,final UserT user,Session session)
	{
		Map map=new HashMap();
		if(user.getSname()!=null)
		{
			map.put("sname", user.getSname());
		    hql.append(" and u.sname =:sname");
		}
		if(user.getSpassword()!=null)
		{
			map.put("spassword", user.getSpassword());
		    hql.append(" and u.spassword =:spassword");
		}
		Query query = session.createQuery(hql.toString());
		
		Iterator it = map.keySet().iterator();

         while (it.hasNext()){

         Object key = it.next(); 

         query.setParameter(key.toString(), map.get(key)); 

         }
         return query;
	}

 


	public UserT merge(UserT detachedInstance) {
		log.debug("merging UserT instance");
		try {
			UserT result = (UserT) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	

	public static UserTDAO getFromApplicationContext(ApplicationContext ctx) {
		return (UserTDAO) ctx.getBean("UserTDAO");
	}
}